<template>
  <a-tabs v-model:activeKey="activeKey" tab-position="left" class="h-full">
    <a-tab-pane key="1" tab="流程审核" class="h-full pd-20px">
      <a-modal width="600px" title="信息提示" v-model:open="msgModalOpen" destroyOnClose>
        <div class="msgModal">
          <p>
            <CheckCircleOutlined
              class="mr-8px"
              :style="{
                color: errorMsg.resType == 'success' ? '#55a532' : '#bd2c00',
                fontSize: '24px',
              }"
            />{{ errorMsg.resType == 'success' ? '操作成功' : '操作失败' }}
          </p>
          <p>
            <InfoCircleOutlined
              class="mr-8px"
              :style="{
                color: errorMsg.resType == 'success' ? '#55a532' : '#bd2c00',
                fontSize: '24px',
              }"
            />{{ errorMsg.resTypeMsg }}
          </p>
          <p>
            <SnippetsOutlined
              class="mr-8px"
              :style="{
                color: errorMsg.resType == 'success' ? '#55a532' : '#bd2c00',
                fontSize: '24px',
              }"
            />{{
              errorMsg.resType == 'success'
                ? '您可以在已办任务中，查看流程审核轨迹。'
                : '您可联系管理员检查流程配置是否正确。'
            }}
          </p>
        </div>

        <template #footer>
          <a-button
            type="primary"
            v-if="errorMsg.resType == 'error'"
            @click="() => (msgModalOpen = false)"
            >确定</a-button
          >
          <a-button
            type="primary"
            v-if="errorMsg.resType == 'success'"
            :loading="loading"
            @click="handleMsgModalOk"
            >确定</a-button
          >
        </template>
      </a-modal>
      <headerToolbar
        v-if="!props.previewConfig.isDraft"
        :previewConfig="previewConfig"
        @cancel="handleMsgModalOk"                
      >
      </headerToolbar>      
      <a-layout>
        <a-layout-content :style="contentStyle">
          <a-card>
            <div>
              <preview
                v-if="showPreview && previewConfig?.form_type == '0'"
                ref="previewRef"
                v-bind="{ ...previewFormObj }"
              >
              </preview>
              <iframe
                ref="previewIframeRef"
                v-if="previewConfig.form_type == '1'"
                :src="previewIframeUrl"
                class="h-full w-full"
                frameborder="0"
              ></iframe>
            </div>
          </a-card>
        </a-layout-content>
        <a-layout-sider width="25%" :style="siderStyle">
          <monitorToolbar
            ref="approveToolbarRef"
            :previewConfig="previewConfig"
            :previewFormObj="previewFormObj"
            :saveFormData="saveFormData"
            @cancel="handleMsgModalOk"
          ></monitorToolbar>
        </a-layout-sider>
      </a-layout>
    </a-tab-pane>
    <a-tab-pane key="2" tab="审批记录">
      <a-tabs v-model:activeKey="recordKey" @change="handRecordTabs">
        <a-tab-pane tab="审批记录" key="3">
          <a-steps v-model:current="current" direction="vertical" :items="items"> </a-steps>
        </a-tab-pane>
        <a-tab-pane tab="流程预估" key="4">
          <!--  <a-steps v-model:current="current" direction="vertical" :items="estimateItems">
          </a-steps> -->
          <a-table :dataSource="dataSource" :columns="columns" :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'activityName'">
                <a>
                  {{ record.activityName }}
                </a>
              </template>
              <template v-else-if="column.key === 'activityStatus'">
                <span>

                  <a-tag                     
                    :color = getTagColor(record.activityStatus)
                  >
                    {{ record.activityStatus  }}
                  </a-tag>
                </span>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane tab="流程图" key="5">
          <a-alert
            message="审批轨迹图"
            type="success"
            class="mb-16px text-18px font-bold"
          ></a-alert>
          <a-card class="mb-20px">
            <a-image :fallback="constants.noPic" :src="trackImg" />
          </a-card>
          <a-alert
            message="审批轨迹表"
            type="success"
            class="mb-16px text-18px font-bold"
          ></a-alert>
          <a-card> </a-card>
        </a-tab-pane>
        <a-tab-pane tab="基本信息" key="6">
          <a-form :model="basicInfo" v-bind="layout" name="basicInfos">
            <a-form-item label="发起人">
              {{ basicInfo.createName }}
            </a-form-item>
            <a-form-item label="申请部门">
              {{ basicInfo.departName }}
            </a-form-item>
            <a-form-item label="所属模版">
              {{ basicInfo.flowName }}
            </a-form-item>
            <a-form-item label="当前节点">
              {{ basicInfo.nodeName }}
            </a-form-item>
            <a-form-item label="创建时间">
              {{ basicInfo.startTime }}
            </a-form-item>
            <a-form-item label="流程编号">
              {{ basicInfo.serialNumber }}
            </a-form-item>
            <a-form-item label="流程状态">
              {{ basicInfo.workStatus }}
            </a-form-item>
            <a-form-item label="当前表单">
              {{ basicInfo.formName }}
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane tab="访问统计" key="7"> </a-tab-pane>
      </a-tabs>
    </a-tab-pane>
  </a-tabs>
</template>

<script lang="tsx" setup>
import { ref, nextTick, reactive, onMounted, watch } from 'vue';
import type { CSSProperties } from 'vue';
import { SchemaForm } from '@/components/core/schema-form';
import { schemas } from './useApprovalForm';
import { SnippetsOutlined, CheckCircleOutlined, InfoCircleOutlined } from '@ant-design/icons-vue';
import { approvalTableStates } from './useApprovalTable';
import type { SchemaFormProps, SchemaFormInstance } from '@/components/core/schema-form';
import preview from '@/components/form/preview.vue';
import { isEmpty, isNullOrUnDef } from '@/utils/is/';
import { getTrack, getApprovalTracks, downLoadFile, getUserTaskTrack,
         getWorkflowBasicInfo,getWorkflowEstimate
 } from '@/api/flow/review';
import { useTable } from '@/components/core/dynamic-table';
import constants from '@/utils/constants';
import monitorToolbar from './monitorToolbar.vue';
import headerToolbar from './headerToolbar.vue';
import { StepProps } from 'ant-design-vue';


const current = ref<number>(0);

const approveToolbarRef = ref()
const items = reactive([]) as StepProps[];
const estimateItems = reactive([]) as StepProps[];
const dataSource = ref([]);


const columns = [
          {
            title: '节点名称',
            dataIndex: 'activityName',
            key: 'activityName',
          },
          {
            title: '节点类型',
            dataIndex: 'activityType',
            key: 'activityType',
          },  
          {
            title: '默认处理人',
            dataIndex: 'operationNames',
            key: 'operationNames',
          },
          {
            title: '处理规则',
            dataIndex: 'operatorRule',
            key: 'operatorRule',
          },
           {
            title: '任务状态',
            dataIndex: 'activityStatus',
            key: 'activityStatus',
          },
           {
            title: '流向',
            dataIndex: 'nextActivityName',
            key: 'nextActivityName',
          },
        ];


const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
};

let basicInfo = reactive({
  createName:'张三丰',
  departName:'研发部',
  flowName:'',
  nodeName:'',
  startTime:'',
  serialNumber:'',
  workStatus:'',
  formName:'',
});



const contentStyle: CSSProperties = {
  color: '#fff',
  backgroundColor: '#fff',
};
const siderStyle: CSSProperties = {
  color: '#fff',
  backgroundColor: '#fff',
  height: '80vh',
};

const props = defineProps({
  previewFormObj: {
    type: Object as any,
    default: {
      itemList: [],
      formConf: {},
      dataJson: {},
    },
  },
  previewConfig: {
    type: Object as any,
    default: {},
  },
});
const emit = defineEmits(['cancel','reload']);

// 当前主键
const bussid = ref('');
// 当前tab页key
const activeKey = ref('1');
const recordKey = ref('3');
const recordLoadInfo = reactive([
  { key: 3, isLoaded: false },
  { key: 4, isLoaded: false },
  { key: 5, isLoaded: false },
  { key: 6, isLoaded: false },
  { key: 7, isLoaded: false }
]);

const handRecordTabs = () => {
  let record = recordLoadInfo.find(item => item.key == recordKey.value);
  //流程图
  if (recordKey.value == 5 && record.isLoaded == false) {
    queryTackPic();
    record.isLoaded = true;
  }
  //审批记录
  if (recordKey.value == 3 && record.isLoaded == false) {
    queryTackList();
    record.isLoaded = true;
  }
  //基本信息
  if (recordKey.value == 6 && record.isLoaded == false) {
    queryBasicInfo();
    record.isLoaded = true;
  }
  //
  if (recordKey.value == 4 && record.isLoaded == false) {
    queryEstimateInfo();
    record.isLoaded = true;
  }
  

}

// 提示信息弹窗
const msgModalOpen = ref(false);
const handleMsgModalOk = () => {
  msgModalOpen.value = false;  
  emit('cancel');
  emit('reload');
};

const handleReload = () => {
  msgModalOpen.value = false;
  emit('reload');
};



const errorMsg = reactive({
  //默认信息类型
  resType: 'suecess',
  //默认提示信息
  resTypeMsg: '',
});

const previewRef = ref(null);
const previewIframeRef = ref(null);
const previewIframeUrl = ref(undefined);


// 轨迹图
const trackImg = ref<any>();

const showPreview = ref(false);
const loading = ref(false);

const dynamicForm = ref<SchemaFormInstance>();
const formProps: SchemaFormProps = {
  schemas,
  labelWidth: 120,
  actionColOptions: { span: 24 },
  showActionButtonGroup: false,
};
// 点击提交
function confirm() {
  console.log('dynamicForm.value', dynamicForm.value?.formModel);
  dynamicForm.value?.validate().then(() => console.log('验证通过！'));
}
const saveFormData = () => {
  const res = previewRef.value?.handlerSubForm()
  return res;
}
const  apporveDescription = (item) => {
  return (
    <div>
      <span>{item.userName}  {item.actionName}  {item.rdt}  耗时： {item.duration} </span>
    </div>
  );

}

const estimateDescription = (item) => {
  return (
    <div>
      <span>  审批人： {item.operationNames}  节点类型： {item.activityType} 处理规则： {item.operatorRule}  任务状态：  {item.activityStatus}  下一步： {item.nextActivityName} </span>
    </div>
  );

}

const getTagColor=(stat)=>{
  if(stat==="通过"){
    return "green";
  }
  else if(stat ==="进行中"){
    return "orange";

  }
  else if(stat==="未进行"){
    return "blue";

  }
}



// 获取轨迹图
const queryTackPic = async () => {
  const res = await getTrack({
    processInstanceId: props.previewConfig.procinstid,
    porcessKey: props.previewConfig.processDefinitionId ? props.previewConfig.processDefinitionId : "",
  });
  if (res && res.data) {
    trackImg.value = window.URL.createObjectURL(res.data);
  }
};

// 获取审批记录
const queryTackList = async () => {
  const res = await getUserTaskTrack({
    processInstanceId: props.previewConfig.procinstid,
  });
  if (res && res.result) {
    handTrackList(res.result);
  }
};

const handTrackList = (result) => {
  result.forEach((item) => {
    let step: StepProps = {
      title: item.userTaskName,
      description: apporveDescription(item),
    }
    items.push(step);
  });

}

//获取基本信息
const queryBasicInfo = async () =>{
  const res = await getUserTaskTrack({
    processInstanceId: props.previewConfig.procinstid,    
  });
  if (res && res.result) {
    basicInfo = res.result;    
  }
}
//获取预估信息
const queryEstimateInfo = async () =>{
  const res = await getWorkflowEstimate({
    processInstanceId: props.previewConfig.procinstid,
    processDefinitionId:props.previewConfig.processDefinitionId ? props.previewConfig.processDefinitionId : "",
  });
  if (res && res.result) {    
    dataSource.value = res.result;   
    //dataSource.push(res.result);

  }
}

const handEstimateItems = (result) => {
  result.forEach((item) => {
    let step: StepProps = {
      title: item.activityName,
      description: estimateDescription(item),
    }
    estimateItems.push(step);
  });

}


// 文件下载
const handleFileDownLoad = async (url, filename) => {
  downLoadFile(url, filename);
};

const [DynamicTable, dynamicTableInstance] = useTable(approvalTableStates as any);

watch(
  () => props.previewConfig,
  () => {
    if (props.previewConfig.form_type == '0') {
      showPreview.value = true;
      loading.value = false;
    }
  },
  {
    immediate: true,
  },
);

onMounted(() => {
  //queryTackPic();
  handRecordTabs();
});
</script>

<style lang="less">
.msgModal {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 30px;

  p {
    width: 400px;
    font-size: 18px;
  }
}
</style>
<style lang="less" scoped>
.flex-buttom-box {
  display: flex;
  flex-wrap: wrap-reverse;
  gap: 10px;
}
</style>